'use strict';
require('./index.css')
require('page/common/nav/index.js')
require('page/common/header/index.js')
var _mm          = require('util/mm.js')
var _product     = require('service/product-service.js')
var _cart        = require('service/cart-service.js')
var template     = require('./index.string')

var page = {
    data : {
        productId : _mm.getUrlParam('productId') || ' '
    },
    init : function(){
        this.onLoad();
        this.bindEvent();
    },
    onLoad : function(){
        // 如果没有传入productid  自动跳回首页
        if(!this.data.productId){
            _mm.goHome()
        }
        this.loadDetail()
    },
    //加载商品详情的数据
    loadDetail : function(){
        var _this = this,
            html  = "";

         $('.page-wrap').html('<div class="loading"></div>')
        //  请求detail地址
        _product.getProductDetail(this.data.productId,function(res){
            // 缓存detail的数据
            _this.data.dateilInfo = res;
            //处理res里面的图片数据
            _this.filter(res)
            html = _mm.renderHtml(template,res)
            $('.page-wrap').html(html)
        },function(Msg){
             $('.page-wrap').html('<p class="err-Tip">啊哦,您要的商品找不到了~</p>')
        })
    },
    filter : function(data){
        data.subImages = data.subImages.split(',')
    },

    bindEvent : function(){
        var _this = this;
        // 图片预览
        $(document).on('mouseenter','.p-img-item',function(){
           var imgUrl = $(this).find('.p-img').attr('src')
           $('.main-img').attr('src',imgUrl)
        })
        // 加减库存
        $(document).on('click','.p-count-btn',function(){
            var type      = $(this).hasClass('plus') ? 'plus' : 'minus',
                $pCount   = $('.p-count'),
                currCount = parseInt($pCount.val()),  //获取到本来input里面的值
                minCount  = 1,
                maxCount  = _this.data.dateilInfo.stock || 1 ;
            if( type==='plus' ){
                 $pCount.val(currCount < maxCount ? currCount+1 : maxCount)
            }
            else if(type==='minus'){
                 $pCount.val(currCount > minCount ? currCount-1 : minCount)
            }
        })
        // 加入购物车
           $(document).on('click','.cart-add',function(){
                _cart.addToCart({
                    productId : _this.data.productId,
                    count     : $('.p-count').val()
                },function(res){
                    window.location.href = './result.html?type=cart-add'
                },function(errMsg){
                    _mm.errorTips(errMsg)
                })
           })
    }
}


$(function(){
    page.init()
})